package com.bw.finance.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/msg/{uid}")
public class MsgWsService {
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("uid")String uid){
        sessionPools.put(uid,session);
        System.out.println(uid+":用户已上线！！！");
    }

    @OnClose
    public void onColse( @PathParam("uid")String uid){
        sessionPools.remove(uid);
        System.out.println(uid+":用户已下线！！！");
    }
    @OnMessage
    public void onMessage(String message){
        System.out.println(message);
    }

    @OnError
    public void onError(Throwable throwable){
        System.out.println("发生错误："+throwable.toString());
    }

    //发送消息
    public void sendMessage(String uid, String message){ //给指定用户发送消息
        Session session = sessionPools.get(uid);
        session.getAsyncRemote().sendText(message);
    }
}
